var sceneReadyBehavior = require('../behavior-scene/scene-ready');
import { activationCode } from "../../server/api/common.js";
import '../effect-bgTransparent.js';

Page({
  behaviors: [sceneReadyBehavior],
  data: {
    xmlCode: '',
    videoImageUrl: "",
    videoUrl: "",
    modelImageUrl: "",
    modelUrl: "",
    position: "",
    scale: "",
    rotation: "",
    code: "",
    isCodeProcessed: false // 新增标志位
  },

  onLoad(options) {
    console.log(options, "options");
    if (options.q) {
      const url = decodeURIComponent(options.q);
      const queryString = url.split('?')[1];
      const params = {};
      queryString.split('&').forEach(param => {
        if (param) {
          const [key, value] = param.split('=').map(decodeURIComponent);
          if (key) {
            params[key] = value || ''; // 如果值为空，则赋予空字符串
          }
        }
      });
      // 获取参数，并设置默认值
      const code = params['code'] || null;
      this.setData({ code: code }, () => {
        if (!this.data.isCodeProcessed) {
          this.bindCode(code);
          this.setData({ isCodeProcessed: true }); // 设置标志位为已处理
        }
      });
    } else {
      const itemString = options.item;
      const item = JSON.parse(itemString);
      this.initAr(item);
    }
  },

  onShow() {
    // 检查是否有未处理的激活码并且标志位为false
    if (this.data.code && !this.data.isCodeProcessed) {
      this.bindCode(this.data.code);
      this.setData({ isCodeProcessed: true }); // 设置标志位为已处理
    }
  },

  bindCode(code) {
    activationCode({code,type:1}).then(res => {
      console.log(res,"res");
      if (res.data.data.code === 0) {
        this.initAr(res.data.data.data);
      } else {
        wx.showModal({
          content: res.data.data.massage,
          showCancel: false,
          confirmText: "关闭",
          success: res => {
            if (res.confirm) {
              wx.reLaunch({
                url: "/pages/home/home"
              });
            }
          }
        });
      }
    }).catch(err => {
      console.error("Activation code binding failed:", err);
    });
  },

  initAr(item) {
    console.log(item, "item");
    if (item.arType === 1) {
      this.setData({
        videoImageUrl: item.image,
        videoUrl: item.video
      });
    } else if (item.arType === 2) {
      this.setData({
        modelImageUrl: item.image,
        modelUrl: item.video,
        position: item.position,
        scale: item.scale,
        rotation: item.angle,
      });
    }
    // this.getStatusBarHeight();
  },

  resetCodeProcessedFlag() {
    this.setData({ isCodeProcessed: false });
  }
});